﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.Departments.Repositories;
using mozhi.smarterp.AuthorCenter.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.AuthorCenter.Departments
{
    public class DepartmentRepository : EfCoreRepository<AuthorCenterDbContext, Department, Guid>, IDepartmentRepository
    {
        public DepartmentRepository(IDbContextProvider<AuthorCenterDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<Department> FindAsync(string code, string name, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var department = await dbContext.Set<Department>().AsNoTracking()
                .WhereIf(!code.IsNullOrEmpty(), x => x.Code == code)
                .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
                .FirstOrDefaultAsync();

            return department;
        }

        public async Task<int> GetCountAsync(string code, string name, Guid? parentId = null, Guid? excludeId = null, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<Department>().AsNoTracking()
                .WhereIf(!code.IsNullOrEmpty(), x => x.Code == code)
                .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
                .WhereIf(excludeId.HasValue, x => x.Id != excludeId)
                .WhereIf(parentId.HasValue, x => x.ParentId == parentId)
                .CountAsync();

            return count;
        }

        public async Task<List<Department>> GetListAsync(string code, string name, Guid? parentId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var departments = await dbContext.Set<Department>().AsNoTracking()
               .WhereIf(!code.IsNullOrEmpty(), x => x.Code == code)
               .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
               .WhereIf(parentId.HasValue , x=>x.ParentId == parentId)
               .ToListAsync();

            return departments;
        }
    }
}
